package com.market.sys.api.client;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.market.sys.common.Result;
import com.market.sys.entity.*;
import com.market.sys.service.*;
import com.market.sys.util.EmptyUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xd
 * @since 2024-03-26
 */
@RestController
@RequestMapping("/sys/notification")
public class NotificationController {

    @Resource
    private INotificationService notificationService;

    @Resource
    private IBoothService boothService;

    @Resource
    private IContractService contractService;

    @Resource
    private IUserService userService;

    @Resource
    private IProvinceService provinceService;

    @Resource
    private ICityService cityService;

    @Resource
    private ICountyService countyService;

    @Resource
    private IStreetService streetService;


    @PostMapping("/fetchCount")
    public Result<?> fetchCount(@RequestBody Map<String, Object> paramMap){
        String userId = String.valueOf(paramMap.get("userId"));
        return Result.success(notificationService.query().eq("user_id",userId).eq("state", 0).count());
    }

    @PostMapping("/fetchListByUserId")
    public Result<?> fetchListByUserId(@RequestBody Map<String, Object> paramMap){
        List<Notification> notificationList = notificationService.query().eq("user_id", paramMap.get("userId"))
                .orderByDesc("notified_at").list();
        User user = userService.query().eq("id", paramMap.get("userId")).one();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Notification notification : notificationList) {
            Map<String, Object> map = new HashMap<>();
            Booth booth = boothService.query().eq("id", notification.getRelatedId()).one();
            Contract contract;
            if (user.getUserRole() == 0){
                contract = contractService.query().eq("booth_id", notification.getRelatedId())
                        .one();
            }else {
                contract = contractService.query().eq("booth_id", notification.getRelatedId())
                        .one();
            }
            map.put("notification", notification);
            map.put("contract", contract);
            map.put("booth", booth);
            map.put("sender", userService.query().eq("id", notification.getSenderId()).one());
            map.put("user", userService.query().eq("id", notification.getUserId()).one());
            if (BeanUtil.isNotEmpty(contract)){
                map.put("needPay", getNeedPay(booth.getLocation(), booth, contract));
            }else {
                map.put("needPay", 0);
            }
            mapList.add(map);
        }

        return Result.success(mapList);
    }

    @PostMapping("/delete")
    public Result<?> delete(@RequestBody Map<String, Object> paramMap){
        if (notificationService.remove(new LambdaQueryWrapper<Notification>().eq(Notification::getId,paramMap.get("id")))){
            return Result.success("删除成功");
        }else {
            return Result.error("删除失败");
        }
    }


    public BigDecimal getNeedPay(String location, Booth booth, Contract contract){
        BigDecimal needPay = null;
        if (!location.contains("-")) {
            // 如果不包含 “-” 符号，则证明是申请的省的摊位
            Province province = provinceService.query().eq("province_name", location).one();
            needPay = ((booth.getRentalFee().multiply(booth.getArea())).add(booth.getExtraFee())).multiply(province.getLevel());
            needPay = needPay.multiply(BigDecimal.valueOf(contract.getRentalTerm()));
        } else {
            // 包含 “-”，则分割
            String[] locationSplits = location.split("-");
            if (locationSplits.length == 4) {
                // 长度是四的话，就证明是街道
                Street street = streetService.query().eq("street_name", locationSplits[3]).one();
                County county = countyService.query().eq("id", street.getCountyId()).one();
                var city = cityService.query().eq("id", county.getCityId()).one();
                Province province = provinceService.query().eq("id", city.getProvinceId()).one();

                BigDecimal provinceLevel = province.getLevel();
                BigDecimal cityLevel = city.getLevel();
                BigDecimal countyLevel = county.getLevel();
                BigDecimal streetLevel = street.getLevel();

                needPay = (((((booth.getRentalFee().multiply(booth.getArea())).add(booth.getExtraFee()))
                        .multiply(provinceLevel))
                        .multiply(cityLevel)).multiply(countyLevel)).multiply(streetLevel);
                needPay = needPay.multiply(BigDecimal.valueOf(contract.getRentalTerm()));
            } else if (locationSplits.length == 3) {
                County county = countyService.query().eq("county_name", locationSplits[2]).one();
                City city = cityService.query().eq("id", county.getCityId()).one();
                Province province = provinceService.query().eq("id", city.getProvinceId()).one();

                BigDecimal provinceLevel = province.getLevel();
                BigDecimal cityLevel = city.getLevel();
                BigDecimal countyLevel = county.getLevel();

                needPay = (((((booth.getRentalFee().multiply(booth.getArea())).add(booth.getExtraFee()))
                        .multiply(provinceLevel))
                        .multiply(cityLevel)).multiply(countyLevel));
                needPay = needPay.multiply(BigDecimal.valueOf(contract.getRentalTerm()));
            } else if (locationSplits.length == 2) {
                City city = cityService.query().eq("city_name", locationSplits[1]).one();
                Province province = provinceService.query().eq("id", city.getProvinceId()).one();

                BigDecimal provinceLevel = province.getLevel();
                BigDecimal cityLevel = city.getLevel();

                needPay = ((((booth.getRentalFee().multiply(booth.getArea())).add(booth.getExtraFee()))
                        .multiply(provinceLevel))
                        .multiply(cityLevel));
                needPay = needPay.multiply(BigDecimal.valueOf(contract.getRentalTerm()));
            }
        }

        return needPay;
    }
}
